<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible &&
        !consumeDetailInfo.visible &&
        !purchReturnInfo.visible &&
        !receivingDetailInfo.visible &&
        !detailInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
          <template v-slot:filter-createTime>
            <el-date-picker
              @change="timeChange"
              v-model="time"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              align="right"
              start-placeholder="创建开始时间"
              end-placeholder="创建结束时间"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59),
              ]"
            ></el-date-picker>
          </template>
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList"> </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tabIndex="true"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :checkBox="false"
        :handle="tableInfo.handle"
        :summary="proxy.$permission('pendReceiptOrder:price')"
        :summaryFieldList="tableInfo.summaryFieldList"
        @pageInfo="pageInfo"
        :all-summary="true"
        :all-summary-data="allSummaryData"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </TableContainer>
    </div>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :tableRow="modifyInfo.tableRow"
      :title="modifyInfo.title"
      @returnModify="getList"
    />
    <ReceivingDetail
      v-if="receivingDetailInfo.visible"
      v-model:visible="receivingDetailInfo.visible"
      :id="receivingDetailInfo.id"
      :title="receivingDetailInfo.title"
      @returnModify="getList"
    />
    <ConsumeDetail
      v-if="consumeDetailInfo.visible"
      v-model:visible="consumeDetailInfo.visible"
      :id="consumeDetailInfo.id"
      :title="consumeDetailInfo.title"
      @returnModify="getList"
    />
    <PurchReturnDetail
      v-if="purchReturnInfo.visible"
      v-model:visible="purchReturnInfo.visible"
      :purchReturnId="purchReturnInfo.id"
      @returnModify="getList"
    />
    <!-- 明细信息 -->
    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :orderId="detailInfo.orderId"
      :detailsRow="detailInfo.detailsRow"
      @returnBack="getList"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio label="page">当前页数据</el-radio>
          <el-radio label="all">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="pendReceiptOrder">
import ReceivingDetail from '@/views/stock/receiving/detail'
import ConsumeDetail from '@/views/stock/consumeOrder/detail'
import PurchReturnDetail from '@/views/purch/return/detail'
import Modify from '@/views/receiptManage/receiptOrder/modify'
import detail from './detail'
import {
  getPendReceiptOrderCustomizeListPage,
  getPendReceiptOrderPage,
  oneButtonWriteOff,
  receiptPendReceiptOrderExcel,
  getPendReceiptOrderSumAount,
} from '@/api/receipt'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getSupplierAll } from '@/api/core'
const { proxy } = getCurrentInstance()
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const time = ref([])
const allSummaryData = ref({
  data: [],
  fieldList: [
    {
      label: '开票总金额',
      value: 'sumStockAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
const detailInfo = ref({
  visible: false,
  orderId: '',
  detailsRow: {},
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      supplierAuth: {
        asTbName: 'pend_receipt_order',
        columnName: 'supplier_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
    queryParams: {},
  },
  searchList: [],
  btnList: [
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('pendReceiptOrder:exportExcel'),
    },
    {
      type: 'button',
      label: '一键冲销',
      event: handleWriteOff,
      show: proxy.$permission('pendReceiptOrder:writeOff'),
    },
  ],
  searchBtn: [
    { type: 'button', label: '搜索', event: _search },
    { type: 'button', label: '高级查询', event: _advancedSearchShow },
    { type: 'button', label: '重置', event: _clearSearch },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: null,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '开票',
        event: createReceiptOrder,
        show: proxy.$permission('pendReceiptOrder:createReceiptOrder'),
        ifRender: function (row) {
          return (
            row.availableQty > 0 &&
            Number(systemConfig.receipt_together_config) !== 1
          )
        },
      },
      {
        label: '冲销详情',
        event: handleDetailForWriteOff,
        // show: true,
        show: proxy.$permission('pendReceiptOrder:writeOffDetails'),
        ifRender: function (row) {
          return row.writeOffCalcQty > 0
        },
      },
    ],
  },
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: 'page',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const modifyInfo = ref({
  visible: false,
  title: '',
  tableRow: {},
})
const receivingDetailInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const consumeDetailInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const purchReturnInfo = ref({
  visible: false,
  id: '',
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'receiptOrder' && el.url === val.url) {
                modifyInfo.valu.visible = false
                // detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  // detailInfo.value.visible = true
                  let data = {
                    id: val.businessId,
                  }
                  // detailInfo.value.tableRow = data
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    { deep: true, immediate: true }
  )
})
onDeactivated(() => {
  stopWatch()
})
setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'pend_receipt_order_status',
      show: false,
      hidden: true,
    },
    baseProductTypeValue: {
      label: '产品类型',
      value: 'baseProductTypeValue',
      asValue: 'baseProductType',
      componentType: 'select-model',
      code: 'new_product_type',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function getSummary() {
  let params = {}
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(filterInfo.value.query)
    params.queryMap = {}
  } else {
    params = filterInfo.value.query
  }
  getPendReceiptOrderSumAount(params).then((res) => {
    if (res && res.success) {
      if (res.data && res.data[0] !== null) {
        allSummaryData.value.data = [{ sumStockAmount: res.data }]
      } else {
        allSummaryData.value.data = []
      }
    }
  })
}
function _search() {
  search()
}
function _advancedSearchShow() {
  advancedSearchShow()
}
function _clearSearch() {
  clearSearch()
}

const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
  getSummary()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
  getSummary()
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}

async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  _filterInfo.query.queryMap = {}
  let arr = [
    {
      asTbName: 'pend_receipt_order',
      columnName: 'supplier_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'supplierAuth',
    },
  ]
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}

function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey:
      'pendReceiptOrderList-com.slip.spd.entity.vo.receipt.PendReceiptOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getPendReceiptOrderCustomizeListPage
      getList()
    }
  })
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.createTimeGreater = val[0]
    filterInfo.value.query.createTimeLess = val[1]
  } else {
    filterInfo.value.query.createTimeGreater = ''
    filterInfo.value.query.createTimeLess = ''
  }
}
function pageInfo(obj) {
  page.value = obj
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = 'page'
}
function handleClose() {
  dialogInfo.value.visible = false
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcelList() {
  let query = {
    customizeDto: proxy.$fn.delEmptyAttribute(filterInfo.value.query),
  }
  let params = {
    ...query,
    ...page.value,
    page: dialogInfo.value.flag === 'page' ? true : false,
  }
  receiptPendReceiptOrderExcel(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function showDetail(row) {
  // 1-是采购退货 15-收货单 25-消耗单
  if (row.orderType === 1) {
    purchReturnInfo.value.id = row.orderId
    purchReturnInfo.value.visible = true
  } else if (row.orderType === 25) {
    //跳转到消耗
    consumeDetailInfo.value.id = row.orderId
    consumeDetailInfo.value.visible = true
    consumeDetailInfo.value.title = '消耗明细'
  } else if (row.orderType === 15) {
    //跳转入库
    receivingDetailInfo.value.id = row.orderId
    receivingDetailInfo.value.visible = true
    receivingDetailInfo.value.title = '收货单明细'
  }
}
function createReceiptOrder(row) {
  modifyInfo.valu.title = '新增发票单'
  modifyInfo.valu.visible = true
  modifyInfo.valu.tableRow = row
}
// 冲销
function handleWriteOff() {
  oneButtonWriteOff().then((res) => {
    if (res.success) {
      getList()
    }
  })
}
// 冲销详情
function handleDetailForWriteOff(row) {
  detailInfo.value.orderId = row.id
  detailInfo.value.detailsRow = row

  detailInfo.value.visible = true
}
</script>

<style scoped></style>
